package channelHandler

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Hex"
	"github.com/dop251/goja"
	"go-fox-edge-channel-tcp-server-v2/channelEngine/scriptEngine"
)

type ChannelHandler struct {
	Manufacturer string
	DeviceType   string

	SplitHandler string

	Notify *OperateEntityNotify
}

func (e *ChannelHandler) GetHeaderLength() (int, error) {
	// 获得JS引擎
	engine := scriptEngine.GetScriptEngine(e.Manufacturer, e.DeviceType, e.SplitHandler)
	if engine == nil {
		return 0, errors.New("未定义函数：找不到对应的【报文分拆】操作splitHandler")
	}

	// 执行JSP脚本中的函数：getHeaderLength
	encode, ok := goja.AssertFunction(engine.Get("getHeaderLength"))
	if !ok {
		return 0, errors.New("未定义函数：getHeaderLength")
	}

	// 执行函数
	res, err := encode(goja.Undefined())
	if err != nil {
		return 0, err
	}

	return int(res.ToInteger()), nil
}

func (e *ChannelHandler) InvalidHeader(pack []byte) (bool, error) {
	engine := scriptEngine.GetScriptEngine(e.Manufacturer, e.DeviceType, e.SplitHandler)
	if engine == nil {
		return false, errors.New("未定义函数：找不到对应的【报文分拆】操作splitHandler")
	}

	// 执行JSP脚本中的函数：getHeaderLength
	encode, ok := goja.AssertFunction(engine.Get("isInvalidPack"))
	if !ok {
		return false, errors.New("未定义函数：isInvalidPack")
	}

	data := Hex.EncodeToString(pack)

	// 执行函数
	res, err := encode(goja.Undefined(), engine.ToValue(data))
	if err != nil {
		return false, err
	}

	return res.ToBoolean(), nil
}

func (e *ChannelHandler) GetPackLength(pack []byte) (int, error) {
	engine := scriptEngine.GetScriptEngine(e.Manufacturer, e.DeviceType, e.SplitHandler)
	if engine == nil {
		return 0, errors.New("未定义函数：找不到对应的【报文分拆】操作splitHandler")
	}

	// 执行JSP脚本中的函数：getHeaderLength
	encode, ok := goja.AssertFunction(engine.Get("getPackLength"))
	if !ok {
		return 0, errors.New("未定义函数：getPackLength")
	}

	data := Hex.EncodeToString(pack)

	// 执行函数
	res, err := encode(goja.Undefined(), engine.ToValue(data))
	if err != nil {
		return 0, err
	}

	return int(res.ToInteger()), nil
}
